import React, { memo, useCallback, useEffect, useState } from 'react'
import proptypes from 'prop-types'
import { Image } from 'antd'
import { FallPictureWrapper } from './style'
import Masonry from 'react-masonry-component'
import NProgress from 'nprogress'
import LazyLoad from 'react-lazyload'

const masonryOptions = {
  transitionDuration: 0
}

const imagesLoadedOptions = { background: '.my-bg-image-el' }

function B_FallPicture(props) {
  const { walls = [] } = props
  const [imageTotal, setImageTotal] = useState(walls.length || 0)

  useEffect(() => {
    if (walls.length === 0) {
      NProgress.done()
      NProgress.start()
    } else if (walls.length && imageTotal >= walls.length) {
      NProgress.done()
    }
  }, [imageTotal, walls.length])

  // 监听图片加载完成
  const handleImageLoaded = useCallback(() => {
    setImageTotal(imageTotal + 1)
  }, [setImageTotal, imageTotal])

  // 监听图片加载错误
  const handleImageErrored = useCallback(() => {
    setImageTotal(imageTotal + 1)
  }, [setImageTotal, imageTotal])

  return (
    <FallPictureWrapper>
      <Masonry
        className={'my-gallery-class'}
        elementType={'ul'}
        options={masonryOptions}
        disableImagesLoaded={false}
        updateOnEachImageLoad={false}
        imagesLoadedOptions={imagesLoadedOptions}
      >
        <Image.PreviewGroup>
          {walls.map((item) => {
            return (
              <li key={item.id} className="image-element-class">
                <LazyLoad>
                  <Image
                    placeholder={true}
                    width={300}
                    src={item.url}
                    onLoad={handleImageLoaded}
                    onError={handleImageErrored}
                  />
                </LazyLoad>
              </li>
            )
          })}
        </Image.PreviewGroup>
      </Masonry>
    </FallPictureWrapper>
  )
}

B_FallPicture.propTypes = {
  walls: proptypes.array
}

export default memo(B_FallPicture)
